package com.wnxy.pms.member.core.exception;

import com.wnxy.pms.common.api.Result;
import com.wnxy.pms.common.api.enums.impl.ResultCode;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全局异常处理类, 可以处理指定类型的异常，如果没有找到指定类型的异常，处理所有的Exception异常
 */
@RestControllerAdvice
public class GlobalException {

    /**
     * 处理BusinessException类型的异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result handlerBusinessException(BusinessException e){
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        List<FieldError> fieldErrorList = e.getBindingResult().getFieldErrors();
        Map<String, String> map = fieldErrorList.stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return Result.fail(ResultCode.PARAM_IS_BLANK,map);
    }

    /**
     * 捕获指定的异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result handlerParamsException(IllegalArgumentException e){
        e.printStackTrace();
        return Result.fail(ResultCode.PARAM_IS_BLANK);
    }

    /**
     * 当前面的异常都不匹配，执行这里
     */
    @ExceptionHandler(Exception.class)
    public Result handlerParamsException(Exception e){
        e.printStackTrace();
        return Result.fail(ResultCode.FAILED,e.getMessage());
    }

}
